package com.sanqing.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sanqing.bean.Employee;
import com.sanqing.dao.EmployeeDAO;
import com.sanqing.factory.EmployeeDAOFactory;

/**
 * Servlet implementation class StatusRecognise
 * 处理登录控制器
 */
@WebServlet("/StatusRecognise")
public class StatusRecognise extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StatusRecognise() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		ServletContext servletContext=getServletContext();//上下文对象
		RequestDispatcher dispatcher=null;//实现服务器端跳转的接口
		
		//获得jsp输入的数据
		String employeeID=request.getParameter("employeeID");
		String password=request.getParameter("password");
		
		/*
		 * 
		 * 点击提交后的处理模块
		 * 
		 */
		//如果没填写ID，则提示输入ID
		if(employeeID==null||"".equals(employeeID))
		{
			
			request.setAttribute("error", "请输入账号");
			dispatcher=servletContext.getRequestDispatcher("/View/statusRecognise.jsp");
			
		}else{
			//如果没有填写密码，则提示
			if(password==null||"".equals(password))
			{
				request.setAttribute("error", "请输入密码");
				dispatcher=servletContext.getRequestDispatcher("/View/statusRecognise.jsp");
				
			}else{
				//开始验证填入的信息
				EmployeeDAO employeeDAO = EmployeeDAOFactory.getEmployeeDAOInstance();
				Employee employee=employeeDAO.findEmployeeById(Integer.parseInt(employeeID));
				
				//如果没找到此id员工，提示信息
				if(employee==null){
					request.setAttribute("error", "没有此员工");
					dispatcher=servletContext.getRequestDispatcher("/View/statusRecognise.jsp");
				}
				else{
					//如果密码正确，跳转到成功页面
					if(password.equals(employee.getPassword())){
						request.getSession().setAttribute("employee", employee);//将employee对象传到前端
						response.sendRedirect("View/index.jsp");
						return;
					}
					//否则密码错误，提示信息
					else{
						request.setAttribute("error", "密码错误");
						dispatcher=servletContext.getRequestDispatcher("/View/statusRecognise.jsp");
					}
				}
				
				
			}
			
		}
		
		dispatcher.forward(request,response);//执行服务器跳转
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
